package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.*;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.*;
import com.itheima.service.db.LogService;
import com.itheima.service.db.UserFreezeService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class UserManager {
    @Reference
    private UserInfoService userInfoService;
    @Reference
    private UserFreezeService userFreezeService;
    @Reference
    private UserService userService;
    @Resource(name = "StringRedisTemplate1")
    private StringRedisTemplate stringRedisTemplate1;
    @Reference
    private LogService logService;
    @Reference
    private UserLocationService userLocationService;

    /**
     * 用户列表数据
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public PageBeanVo findUsers(Integer pageNumber, Integer pageSize) {
        //分页查询
        PageBeanVo pageBeanVo = userInfoService.findUsers(pageNumber, pageSize);
        return pageBeanVo;
    }

    /**
     * 查看用户详情
     *
     * @param userId
     * @return
     */
    public UserInfo findUserById(Long userId) {

        return userInfoService.findById(userId);
    }

    @Reference
    private VideoService videoService;

    /**
     * 分页查询视频列表
     */
    public PageBeanVo findVideoByUserId(Integer pageNumber, Integer pageSize, Long uid) {
        //1.调用分页方法查询数据
        PageBeanVo pageBeanVo = videoService.findVideoByUid(pageNumber, pageSize, uid);
        //2.构建VideoVo对象
        List<Video> items = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Video video : items) {
                VideoVo vo = new VideoVo();
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                //转换
                BeanUtil.copyProperties(userInfo, vo);
                BeanUtil.copyProperties(video, vo);
                //赋值不一样的字段
                //封面
                vo.setCover(video.getPicUrl());
                //签名
                vo.setSignature(video.getText());
                videoVoList.add(vo);
            }
        }
        //赋值数据
        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }


    @Reference
    private MovementService movementService;


    /**
     * 根据传入的用户id和需要查询的动态状态 查询数据封装成vo对象
     *
     * @param pageNumber
     * @param pageSize
     * @param uid
     * @param stateInt
     * @return
     */
    public PageBeanVo findMovementList(Integer pageNumber, Integer pageSize, Long uid, Integer stateInt) {

        //分页查询动态数据
        PageBeanVo pageBeanVo = movementService.findMovementsByUserIdAndState(pageNumber, pageSize, uid, stateInt);

        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> voList = new ArrayList<>();
        //转换
        if (CollectionUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //查询用户的基础数据
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                //封装数据
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);
                //时间的转换
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(movement.getCreated());//将时间戳转换成日期
                String format = simpleDateFormat.format(date);
                vo.setCreateDate(format);
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    /**
     * 动态详情
     *
     * @param movementId
     * @return
     */
    public MovementVo findMovementById(String movementId) {
        Movement movement = movementService.findMovementById(movementId);
        MovementVo vo = new MovementVo();

        if (movement != null) {
            //查询用户的基础数据
            UserInfo userInfo = userInfoService.findById(movement.getUserId());
            //封装数据
            vo.setUserInfo(userInfo);
            vo.setMovement(movement);
            //时间的转换
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(movement.getCreated());//将时间戳转换成日期
            String format = simpleDateFormat.format(date);
            vo.setCreateDate(format);

        }
        return vo;
    }

    @Reference
    private CommentService commentService;

    /**
     * 分页查询评论列表
     *
     * @param movementId
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public PageBeanVo findCommentList(String movementId, Integer pageNumber, Integer pageSize) {
        //查询评论列表数据
        PageBeanVo pageBeanVo = commentService.findMovementComment(movementId, pageNumber, pageSize);
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Comment comment : items) {
                //封装vo
                CommentVo vo = new CommentVo();
                //用户信息
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                vo.setId(comment.getId().toHexString());//评论id
                vo.setAvatar(userInfo.getAvatar());//头像
                vo.setNickname(userInfo.getNickname());//昵称
                vo.setContent(comment.getContent());//评论

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(comment.getCreated());//将时间戳转换成日期
                String format = simpleDateFormat.format(date);
                vo.setCreateDate(format);
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    /**
     * 后台的动态审核 通过
     *
     * @param list
     * @return
     */
    public Map<String, String> messagesPass(List<String> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            for (String movementId : list) {
                //根据动态的ID查找动态的对象
                Movement movement = movementService.findMovementById(movementId);
                //将审核通过的动态的状态码赋值1  1：审核通过
                movement.setState(1);
                //保存修改之后的动态
                movementService.updateMovement(movement);
            }
        }

        Map map = new HashMap();
        map.put("message", "动态审核通过！");
        return map;
    }

    /**
     * 后台的动态审核 不通过
     *
     * @param list
     * @return
     */
    public Map<String, String> massageReject(List<String> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            for (String movementId : list) {
                //根据动态的id查询动态的对象
                Movement movement = movementService.findMovementById(movementId);
                //将审核不通过的动态赋值为2   2：动态审核不通过
                movement.setState(2);
                //将修改后的动态进行保存
                movementService.updateMovement(movement);
            }
        }
        //构造map集合返回数据
        Map map = new HashMap();
        map.put("message", "动态审核不通过！");
        return map;
    }

    /**
     * 用户冻结
     */
    public Boolean freezeOperation(UserFreeze userFreeze) {
        UserInfo userInfo = userInfoService.findById(userFreeze.getUserId());
        userInfo.setUserStatus("2");
        //1为封3天 演示用封10秒
        if (userFreeze.getFreezingTime() == 1) {
            //DateUtil.offsetDay(new Date(),3);
            Long tenSeconds = DateUtil.offsetMillisecond(new Date(), 1000 * 10).getTime();
            userFreeze.setTime(tenSeconds);
        }
        //2为封7天
        if (userFreeze.getFreezingTime() == 2) {
            Long tenSeconds = DateUtil.offsetDay(new Date(), 7).getTime();
            userFreeze.setTime(tenSeconds);
        }
        //3为封永久 别跟我杠你活到99上线等解封
        if (userFreeze.getFreezingTime() == 3) {
            Long tenSeconds = DateUtil.offsetDay(new Date(), 365 * 99).getTime();
            userFreeze.setTime(tenSeconds);
        }
        Boolean flag = userFreezeService.freezeOperation(userFreeze, userInfo);

        //如果冻结登录权限 删除用户token

        User user = userService.findById(userFreeze.getUserId());
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", user.getId());
        tokenMap.put("phone", user.getPhone());
        String token = JwtUtil.createToken(tokenMap);
        String key = ConstantUtil.USER_TOKEN + token;
        if (userFreeze.getFreezingRange() == 1) {
            stringRedisTemplate1.delete(key);
        }

        return flag;
    }

    /**
     * 用户解冻
     */
    public Boolean freezeUnseal(UserThaw userThaw) {
        UserInfo userInfo = userInfoService.findById(userThaw.getUserId());
        userInfo.setUserStatus("1");
        userFreezeService.freezeUnseal(userInfo, userThaw);

        return true;
    }


    /**
     * 查询日志信息
     */
    public PageBeanVo findByLog(Integer pageNumber, Integer pageSize, String startDate, String endDate, String nickName) {
        UserInfo userInfo = null;
        PageBeanVo pageBeanVo = null;
        if (StrUtil.isEmpty(nickName) || "".equals(nickName)) {
            pageBeanVo = logService.findAll(pageNumber, pageSize, startDate, endDate);
        }
        if (StrUtil.isNotEmpty(nickName)) {
            userInfo = userInfoService.findByNickName(nickName);
            Long userId = userInfo.getId();
            pageBeanVo = logService.findByNickName(pageNumber, pageSize, startDate, endDate, userId);
        }
        List<Log> items = (List<Log>) pageBeanVo.getItems();
        List<LogListVo> logListVoList = new ArrayList<>();
        if (items != null) {
            for (Log log : items) {
                LogListVo logListVo = new LogListVo();
                userInfo = userInfoService.findById(log.getUserId());
                if (userInfo == null) {
                    logListVo.setNickname("--");
                } else {
                    logListVo.setNickname(userInfo.getNickname());
                }
                logListVo.setEquipment(log.getEquipment());
                logListVo.setLogTime(log.getLogTime());
                logListVo.setPlace(log.getPlace());

                if (log.getType().equals("0101")){
                    logListVo.setType("登录操作");
                }else if (log.getType().equals("0102")){
                    logListVo.setType("注册操作");
                }else if (log.getType().equals("0102")){
                    logListVo.setType("注册操作");
                }else if (log.getType().equals("0201")){
                    logListVo.setType("发动态操作");
                }else if (log.getType().equals("0202")){
                    logListVo.setType("浏览动态操作");
                }else if (log.getType().equals("0203")){
                    logListVo.setType("动态点赞操作");
                }else if (log.getType().equals("0204")){
                    logListVo.setType("动态喜欢操作");
                }else if (log.getType().equals("0205")){
                    logListVo.setType("评论操作");
                }else if (log.getType().equals("0206")){
                    logListVo.setType("动态取消点赞操作");
                }else if (log.getType().equals("0207")){
                    logListVo.setType("动态取消喜欢操作");
                }else if (log.getType().equals("0301")){
                    logListVo.setType("发布视频操作");
                }else if (log.getType().equals("0302")){
                    logListVo.setType("视频点赞操作");
                }else if (log.getType().equals("0303")){
                    logListVo.setType("视频取消点赞操作");
                }else if (log.getType().equals("0304")){
                    logListVo.setType("视频评论操作");
                }

                logListVoList.add(logListVo);
            }
        }
        pageBeanVo.setItems(logListVoList);

        return pageBeanVo;
    }


    /**
     * 查询用户地理位置信息
     */
    public Map<String, String> findUserLocation(Long userId) {
        return userLocationService.findUserLocation(userId);
    }
}
